package org.sun.online.internal.common.trace;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class TraceIdUtils {
    public static final String TRACE_ID = "traceId";
    private static final int MAX_ID_LENGTH = 15;
    
    private static final Logger LOGGER = LoggerFactory.getLogger(TraceIdUtils.class);

    /**
     	* 生成 traceId
     */
    private static String genTraceId() {
        return RandomStringUtils.randomAlphanumeric(MAX_ID_LENGTH);
    }

    /**
     	* 设置 traceId
     */
    public static void setTraceId(String traceId) {
        // 如果参数为空，则生成新 ID
        traceId = StringUtils.isBlank(traceId) ? genTraceId() : traceId;
        // 将 traceId 放到 MDC 中
        MDC.put(TRACE_ID, StringUtils.substring(traceId, -MAX_ID_LENGTH));
    }

    /**
     	* 获取 traceId
     */
    public static String getTraceId() {
        // 获取
        String traceId = MDC.get(TRACE_ID);
        // 如果 traceId 为空，则生成新 ID
        return  StringUtils.isBlank(traceId) ? genTraceId() : traceId;
    }
}
